import { defineStore } from "pinia";
import { store } from '@/store';
import type { MsgUserData, MessageDetailData } from "@/api/admin/types";
import type { IActivityListResData } from '@/api/activity/types';
import type { ServiceFormExportDetail } from "@/api/serviceForm/types";
import { getExportFormDetail } from '@/api/serviceForm/index';
import { ServiceFormExportStatusEnum } from "@/enums/serviceFormEnum";
import { uniqBy } from "lodash-es";

interface adminState {
    checkedUserList: MsgUserData[]; // 已选择发送对象
    // 消息发送总人数，总公司数
    totalNumber: {
      personNumber: number;
      companyNumber: number;
    },
    // 当前点击消息-用于消息详情
    currentMsgDetails?: MessageDetailData;
    isResetList: boolean; // 是否需要刷新列表
    taskQueuesList: ServiceFormExportDetail[], // 任务队列
    taskLoading: boolean, // 任务队列是否存在执行任务
    taskTimes: any, // 任务队列轮询
}

const createState = (): adminState => ({
  checkedUserList: [],
  totalNumber: {
    personNumber: 0,
    companyNumber: 0
  },
  currentMsgDetails: undefined,
  isResetList: false,
  taskQueuesList: [], // 任务队列
  taskLoading: false,
  taskTimes: undefined
});


export const useAdminStore = defineStore({
    id: 'admin',
    state: () => createState(),
    getters: {},
    actions: {
      // 设置消息详情, 重新发送 || 发送新消息默认赋值
      setIsResetList(data: boolean){
        this.isResetList = data;
      },
      // 设置消息详情, 重新发送 || 发送新消息默认赋值
      setMsgDetails(data: MessageDetailData){
        this.currentMsgDetails = data;
      },
      // 设置导入导出任务队列
      setTaskQueuesList(data: ServiceFormExportDetail[]) {
        this.taskQueuesList = data;
        this.setTaskTimes();
      },
      // 设置任务队列轮询
      setTaskTimes() {
        clearInterval(this.taskTimes);
        this.taskTimes = undefined;
        // 进行中列表
        const _underwayList = this.taskQueuesList.filter(v=> v.exportStatus === ServiceFormExportStatusEnum.CREATED || v.exportStatus === ServiceFormExportStatusEnum.PROCESSING)
        const taskIds = _underwayList.map(v=> v.taskId);
        if (taskIds.length) {
          this.taskLoading = true;
          // 获取队列中正在进行中的任务
          this.taskTimes = setInterval(async () => {
            const data = await getExportFormDetail(taskIds.join(','));
            this.setTaskQueuesList(uniqBy([...data, ...this.taskQueuesList], 'taskId'))
          }, 2000);
        }else{
          this.taskLoading = false;
        }
      }
    }
})

export function useAdminStoreWithOut() {
    return useAdminStore(store);
}